import React, { Component } from 'react';
import { message, Select, Icon, Modal, Button, Form, Upload, Radio, Input, Table, Popconfirm, Popover } from 'antd';
import "../assets/css/APPManage.css"


import { uploadAppIOS, uploadAppAPK, updateVersionList, delUpdateVersion } from "../assets/js/api.js";
const FormItem = Form.Item;
const Option = Select.Option;
const RadioGroup = Radio.Group;
const { TextArea } = Input;
const loginPath = ""
class AppManagement extends Component {
    constructor(props) {
        super(props);
        this.state = {
            appType: 2,
            //   2:安卓  1:IOS
            appModal: false,
            updataEnd: false,
            fileList: [],
        }
    };

    changeAPPType = (data) => {
        this.setState({
            appType: data.key,
            appModal: false,
        })
    }
    openUpload = () => {
        this.props.form.resetFields()
        this.setState({
            appModal: true,
        })
    }
    closeUpload = () => {
        this.setState({
            appModal: false,
            fileList: []
        })
    }
    updataAPP = (e) => {

        e.preventDefault();
        this.props.form.validateFieldsAndScroll(async (err, values) => {
            if (!err) {
                this.setState({
                    updataEnd: true,
                });

                var funStr = values.addFun.replace(/</g, '&lt;');
                funStr = funStr.replace(/>/g, '&gt;');
                funStr = funStr.replace(/\n|\r\n/g, '<br/>')
                var data = {
                    fileUpload: values.file.file,
                    plateform: 2,
                    // 平台类型： 1：IOS 2：Android
                    content: funStr,
                    type: values.type,
                }

                const fileData = new FormData();

                for (const key in data) {
                    fileData.append(key, data[key]);
                }

                uploadAppAPK(fileData).then((res) => {
                    let data = res.data;
                    if (data.ifsuccess && data.code == 200 || data.code == 201) {
                        message.success(data.msg);
                        this.refs.updataLogs.updataList({
                            platform: 2,
                            pageSize: 10,
                            pageNo: 1,
                        });
                    }
                    if (data.ifsuccess && !(data.code == 200 || data.code == 201)) {
                        message.warning(data.msg);
                    }
                    if (!data.ifsuccess) {
                        message.error("网络延时,请稍后重试");
                    }
                    if (data.code == 10300) {
                        message.error("登陆已失效");
                        // window.location.href = loginPath;
                    }
                    this.setState({
                        updataEnd: false,
                        appModal: false,
                        fileList: []
                    });
                })
            }
        })
    }


    updataAPPIOS = (e) => {
        e.preventDefault();
        this.props.form.validateFieldsAndScroll(async (err, values) => {
            if (!err) {

                this.setState({
                    updataEnd: true,
                });
                var funStr = values.addFun.replace(/</g, '&lt;');
                funStr = funStr.replace(/>/g, '&gt;');
                funStr = funStr.replace(/\n|\r\n/g, '<br/>')
                // 平台类型： 1：IOS 2：Android
                var data = {
                    url: values.url,
                    version: values.version,
                    content: funStr,
                    type: values.type,
                }

                uploadAppIOS(data).then((res) => {
                    let data = res.data;
                    if (data.ifsuccess && data.code == 200 || data.code == 201) {
                        message.success(data.msg);
                        this.refs.updataLogs.updataList({
                            platform: 1,
                            pageSize: 10,
                            pageNo: 1,
                        });
                    }
                    if (data.ifsuccess && !(data.code == 200 || data.code == 201)) {
                        message.warning(data.msg);
                    }
                    if (!data.ifsuccess) {
                        message.error("网络延时,请稍后重试");
                    }
                    if (data.code == 10300) {
                        message.error("登陆已失效");
                        // window.location.href = loginPath;
                    }
                    this.setState({
                        updataEnd: false,
                        appModal: false,
                        fileList: []
                    });
                })
            }
        })
    }


    render() {

        const { getFieldDecorator } = this.props.form;

        const Android = {
            labelCol: { span: 6 },
            wrapperCol: { span: 14 },
        };
        const IOS = {
            labelCol: { span: 6 },
            wrapperCol: { span: 14 },
        };

        const props = {
            onRemove: (file) => {
                this.setState(({ fileList }) => {
                    return {
                        fileList: [],
                    };
                });
            },
            beforeUpload: (file) => {
                this.setState(({ fileList }) => ({
                    fileList: [file],
                }));
                return false;
            },
            fileList: this.state.fileList,
        };


        return (
            <div id="carManagement" >
                <div id="AppContainer">
                    <p id="appTitle">APP版本管理</p>
                    <div id="appInfo">
                        <div id="APPType">
                            <span>类别</span>
                            <Select labelInValue defaultValue={{ key: '2' }} style={{ width: 120 }}
                                onChange={this.changeAPPType}>
                                <Option value="2">安卓</Option>
                                <Option value="1">IOS</Option>
                            </Select>
                        </div>
                        <div id="uploadLast" onClick={this.openUpload}>
                            <Icon type="plus" />
                            上传新版本
                        </div>
                    </div>
                </div>
                <UpdataLog appType={this.state.appType} ref="updataLogs"></UpdataLog>
                {/* 安卓更新 */}
                <Modal title="上传APP版本"
                    visible={this.state.appModal && this.state.appType == 2}
                    confirmLoading={this.state.isLoading}
                    onCancel={this.closeUpload}
                    footer={
                        <div className="deleteBtn">
                            <Button key="back" onClick={this.closeUpload} disabled={this.state.updataEnd}>取消</Button>
                            <Button key="submit" disabled={this.state.fileList.length === 0} onClick={this.updataAPP} type="primary"
                                loading={this.state.updataEnd}>
                                确定
                               </Button>
                        </div>
                    }
                >
                    <div className="layerContainer">
                        <Form>
                            {!this.state.updataEnd || <div className="shadowLayer" ></div>}
                            <FormItem
                                {...Android}
                                label="上传文件"
                            >

                                {getFieldDecorator('file', {
                                    rules: [{ required: (this.state.appType == 2), message: '请选择文件' }],
                                })(
                                    <Upload {...props}>
                                        <Button>
                                            <Icon type="upload" />请选择上传的文件
                                </Button>
                                    </Upload>)}

                            </FormItem>

                            <FormItem
                                {...Android}
                                label="版本号"
                            >
                                {getFieldDecorator('version', {
                                    rules: [{ required: true, message: '请输入版本说明' }],
                                })(
                                    <Input placeholder="请输入版本说明" />)}
                            </FormItem>


                            <FormItem
                                {...Android}
                                label="新增功能"
                            >
                                {getFieldDecorator('addFun', {
                                    rules: [{ required: true, message: '请输入功能说明' }],
                                })(
                                    <TextArea rows={4} autosize={false} id="TextArea" />)}
                            </FormItem>



                            <FormItem
                                {...Android}
                                label="是否强制更新"
                            >
                                {getFieldDecorator('type', {
                                    rules: [{ required: true, message: '请选择是否强制更新' }],
                                })(
                                    <RadioGroup>
                                        <Radio value="1">强制</Radio>
                                        <Radio value="2">不强制</Radio>
                                    </RadioGroup>
                                )}
                            </FormItem>
                        </Form>
                    </div>
                </Modal>


                {/* ios更新 */}
                <Modal title="上传APP版本"
                    visible={this.state.appModal && this.state.appType == 1}
                    confirmLoading={this.state.isLoading}
                    onCancel={this.closeUpload}
                    footer={
                        <div className="deleteBtn">
                            <Button key="back" onClick={this.closeUpload} disabled={this.state.updataEnd}>取消</Button>
                            <Button key="submit" disabled={this.state.url == ""} onClick={this.updataAPPIOS} type="primary"
                                loading={this.state.updataEnd}>
                                确定
                               </Button>
                        </div>
                    }
                >
                    <div className="layerContainer">
                        <Form>
                            {!this.state.updataEnd || <div className="shadowLayer" ></div>}
                            <FormItem
                                {...IOS}
                                label="添url"
                            >
                                {getFieldDecorator('url', {
                                    rules: [{ required: (this.state.appType == 1), message: '请输入软件下载链接' }],
                                })(
                                    <Input placeholder="请输入软件下载链接" />)}
                            </FormItem>

                            <FormItem
                                {...IOS}
                                label="版本号"
                            >
                                {getFieldDecorator('version', {
                                    rules: [{ required: true, message: '请输入版本说明' }],
                                })(
                                    <Input placeholder="请输入版本说明" />)}
                            </FormItem>


                            <FormItem
                                {...IOS}
                                label="新增功能"
                            >
                                {getFieldDecorator('addFun', {
                                    rules: [{ required: true, message: '请输入功能说明' }],
                                })(
                                    <TextArea rows={4} autosize={false} id="TextArea" />)}
                            </FormItem>



                            <FormItem
                                {...IOS}
                                label="是否强制更新"
                            >
                                {getFieldDecorator('type', {
                                    rules: [{ required: true, message: '请选择是否强制更新' }],
                                })(
                                    <RadioGroup>
                                        <Radio value="1">强制</Radio>
                                        <Radio value="2">不强制</Radio>
                                    </RadioGroup>
                                )}
                            </FormItem>
                        </Form>
                    </div>
                </Modal>
            </div>
        )
    }
}






class UpdataLog extends Component {
    constructor(props) {
        super(props);
        this.state = {
            type: 0,
            logList: [],
            columnsAndroid: [{
                title: '名称',
                dataIndex: 'title',
                key: "titleandroid",
                render: (text, record) => {
                    return (
                        <span className="info">芯球泊车APP 安卓版</span>
                    );
                },
            }, {
                title: '版本号',
                dataIndex: 'version',
                key: "version",
            }, {
                title: '增量说明',
                dataIndex: 'addList',
                key: "addList",
                render: (text, record) => {
                    var content = (<div>
                        {record.incrementList ? record.incrementList.map((item, index) => {
                            <p>
                                {item}
                            </p>
                        }) : ''}

                    </div>)
                    return (
                        <Popover content={content} title="增量列表" trigger="hover">
                            <span className="info">详情</span>
                        </Popover>
                    );
                },
            }, {
                title: '新增功能',
                dataIndex: 'content',
                key: "content",
                render: (text, record) => {
                    var content = (<div>
                        <section dangerouslySetInnerHTML={{ __html: record.content }}></section>
                    </div>)
                    return (
                        <Popover content={content} title="新增列表" trigger="hover">
                            <span className="info">新增功能</span>
                        </Popover>
                    );
                },
            }, {
                title: '操作',
                dataIndex: 'id',
                key: "id",
                render: (text, record) => {
                    return (
                        this.state.logList.length > 0
                            ? (
                                <Popconfirm title="确定要删除此软件安装包吗?" okText="确认" cancelText="取消" onConfirm={() => this.deleteAPP(record.id)}>
                                    <a href="javascript:;">删除</a>
                                </Popconfirm>
                            ) : null
                    );
                },
            }],

            columnsIOS: [{
                title: '名称',
                dataIndex: 'title',
                key: "titleios",
                render: (text, record) => {
                    return (
                        <span className="info">芯球泊车APP IOS版</span>
                    );
                },
            }, {
                title: '版本号',
                dataIndex: 'version',
                key: "version",
            }, {
                title: '新增功能',
                dataIndex: 'content',
                key: "content",
                render: (text, record) => {
                    var content = (<div>
                        <section dangerouslySetInnerHTML={{ __html: record.content }}></section>
                    </div>)
                    return (
                        <Popover content={content} title="新增列表" trigger="hover">
                            <span className="info">新增功能</span>
                        </Popover>
                    );
                },
            }, {
                title: '操作',
                dataIndex: 'id',
                key: "id",
                render: (text, record) => {
                    return (
                        this.state.logList.length > 0
                            ? (
                                <Popconfirm title="确定要删除此软件安装包吗?" okText="确认" cancelText="取消" onConfirm={() => this.deleteAPP(record.id)}>
                                    <a href="javascript:;">删除</a>
                                </Popconfirm>
                            ) : null
                    );
                },
            }],



            pagination: {},
            loading: false,
        }
    }
    componentDidUpdate() {
        if (this.state.type != this.props.appType) {
            this.setState({
                type: this.props.appType
            }, () => {
                this.updataList({
                    platform: this.state.type,
                    pageSize: 10,
                    pageNo: 1,
                });
            })
        }
    }
    deleteAPP = (id) => {
        var data = {
            platform: this.state.type,
            id: id
        }
        delUpdateVersion(data).then((res) => {
            let data = res.data;

            if (data.ifsuccess && data.code == 200 || data.code == 201) {
                message.success(data.msg);
                var size = this.state.pagination;
                this.updataList({
                    platform: this.state.type,
                    pageSize: this.state.pagination.pageSize,
                    pageNo: this.state.pagination.current,
                });
            }
            if (data.ifsuccess && !(data.code == 200 || data.code == 201)) {
                message.warning(data.msg);
            }
            if (!data.ifsuccess) {
                message.error(data.msg);
            }
            if (data.code == 10300) {
                message.error("登陆已失效");
                // window.location.href = loginPath;
            }

        })
    }
    tableChange = (pagination, filters, sorter) => {
        const pager = { ...this.state.pagination };
        pager.current = pagination.current;
        this.setState({
            pagination: pager,
        });
        this.updataList({
            platform: this.state.type,
            pageSize: pagination.pageSize,
            pageNo: pagination.current,
        });
    }
    updataList = (params = {}) => {
        updateVersionList(params).then((res) => {
            var data = res.data
            this.setState({
                loading: true,
            })
            if (data.ifsuccess) {
                let data1 = data.result;
                const pagination = { ...this.state.pagination };

                pagination.total = data1.total;
                pagination.pageSize = data1.pageSize;
                pagination.current = data1.pageNum;
                this.setState({
                    loading: false,
                    logList: data1.list,
                    pagination,
                });
            } else {
                message.warning("请求异常,请稍后重试");
            }
        })
    };
    componentDidMount() {
        updateVersionList({
            platform: 1,
            pageSize:10,
            pageNo: 1,
        }).then((res) => {
            var data = res.data
            this.setState({
                loading: true,
            })
            if (data.ifsuccess) {
                let data1 = data.result;
                const pagination = { ...this.state.pagination };

                pagination.total = data1.total;
                pagination.pageSize = data1.pageSize;
                pagination.current = data1.pageNum;
                this.setState({
                    loading: false,
                    logList: data1.list,
                    pagination,
                });
            } else {
                message.warning("请求异常,请稍后重试");
            }
        })
    }
    render() {
        return (
            <div id="logList">
                <Table
                    bordered
                    dataSource={this.state.logList}
                    rowKey={record => record.id}
                    columns={this.state.type == 2 ? this.state.columnsAndroid : this.state.columnsIOS}
                    loading={this.state.loading}
                    onChange={this.tableChange}
                />
            </div>
        );
    }
}
const uploadApp = Form.create()(AppManagement);
export default uploadApp;